<template>
    <el-card>
        <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="100px">
            <el-form-item label="租户id：" prop="tenantId">
                 <el-input v-model="queryParams.tenantId" placeholder="租户id" size="small"></el-input>
            </el-form-item>
            <el-form-item label="租户名称：" prop="tenantName">
                <el-input v-model="queryParams.tenantName" placeholder="租户名称" size="small"></el-input>
            </el-form-item>
             <el-form-item label="联系人：" prop="linkman">
                <el-input v-model="queryParams.linkman" placeholder="联系人" size="small"></el-input>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10">
            <el-col :span="24">
                <div style="margin-bottom: 10px">
                    <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                    <el-button type="danger" plain icon="el-icon-delete" size="small" @click="handleDel($refs.tableRef.selection)">删除</el-button>
                    <el-button plain icon="el-icon-setting" size="small" @click="handleSetting">授权管理</el-button>
                </div>
            </el-col>
        </el-row>
         <el-table :data="tableData" ref="tableRef" style="width: 100%" row-key="id" border size="small">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column prop="tenantId" label="租户id"></el-table-column>
            <el-table-column prop="tenantName" label="租户名称"></el-table-column>
            <el-table-column prop="linkman" label="联系人"></el-table-column>
            <el-table-column prop="contactNumber" label="联系电话"></el-table-column>
            <el-table-column prop="createTime" label="账号额度"></el-table-column>
            <el-table-column prop="updateTime" label="过期时间"></el-table-column>
            <el-table-column prop="domain" label="绑定域名" width="300"></el-table-column>
            <el-table-column label="操作" width="200">
                <template slot-scope="scope"> 
                    <el-button type="text" size="mini" @click="handleView(scope.row)" icon="el-icon-view">查看</el-button>
                    <el-button type="text" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
                    <el-button size="mini" type="text" @click="handleDel(scope.row.id)" icon="el-icon-delete">删除</el-button>
                </template>
           </el-table-column>
        </el-table>
        <el-pagination
            v-show="total>0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="1"
            :page-sizes="[10, 20, 30, 40,50,100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination-container"
            :total="total">
        </el-pagination>
         <el-dialog :title="title" :visible.sync="tenantModal" width="50%">
                <el-form :model="tenantForm" ref="tenantForm" :rules="rules" :disabled="isView">
                     <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item  prop="tenantName" label="租户名称：" :label-width="formLabelWidth" required>
                                <el-input v-model="tenantForm.tenantName" autocomplete="off" size="mini" placeholder="请输入租户名称"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item  prop="linkman" label="联系人：" :label-width="formLabelWidth" required>
                                <el-input v-model="tenantForm.linkman" autocomplete="off" size="mini" placeholder="请输入联系人"></el-input>
                            </el-form-item>
                        </el-col>
                         <el-col :span="12">
                            <el-form-item  prop="contactNumber" label="联系电话：" :label-width="formLabelWidth">
                                <el-input v-model="tenantForm.contactNumber" autocomplete="off" size="mini" placeholder="请输入联系电话"></el-input>
                            </el-form-item>
                         </el-col>
                          <el-col :span="24">
                              <el-form-item  prop="address" label="联系地址：" :label-width="formLabelWidth">
                                  <el-input
                                    v-model="tenantForm.address"
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入联系地址"
                                   >
                                    </el-input>
                              </el-form-item>
                          </el-col>
                        <el-col :span="24">
                            <el-form-item  prop="clientId" label="绑定域名：" :label-width="formLabelWidth">
                                <el-input v-model="tenantForm.domain" autocomplete="off" size="mini" placeholder="请输入绑定域名"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                          <el-form-item label="系统背景">
                              <el-upload
                                class="avatar-uploader"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                               </el-upload>
                          </el-form-item>
                      </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit('tenantForm')" size="small">保存</el-button>
                    <el-button @click="tenantModal = false" size="small">取消</el-button>
                </div>
         </el-dialog>
         <el-dialog title="租户授权配置" width="25%" :visible.sync="powerDialog">
             <el-form :model="powerForm" ref="powerForm">
               <el-form-item label="账号额度：">
                   <el-input-number v-model="powerForm.accountNumber" controls-position="right" placeholder="请输入账号额度" size="small"></el-input-number>
               </el-form-item>
               <el-form-item label="过期时间：">
                    <el-date-picker v-model="powerForm.expireTime" type="datetime" size="small" placeholder="选择过期时间"></el-date-picker>
               </el-form-item>
             </el-form>
             <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="powerSubmit('powerForm')" size="small">提交</el-button>
                <el-button @click="resetForm" size="small">清空</el-button>
            </div>
         </el-dialog>
    </el-card>
</template>

<script>
import { getTenantList,saveTenantForm,deleteTenant,getTenantDetail,settingTenant } from '@/api/system/tenant.api.js'
import {format} from '@/utils/index'
    export default {
       data() {
           return {
                queryParams: {
                    current: 1,
                    size: 10,
                    tenantId: undefined,
                    tenantName: undefined,
                    linkman: undefined
                },
                // 弹窗
                tenantModal: false,
                formLabelWidth: "100px",
                tenantForm: {},
                tableData: [],
                isView: false,
                imageUrl: '',
                rules: {
                    tenantName: [
                        { required: true, message: '请输入租户名称', trigger: 'blur' },
                    ],
                     linkName: [
                        { required: true, message: '请输入联系人名称', trigger: 'blur' },
                    ],
                },
                title: '新增',
                total: 0,
                powerDialog: false,
                powerForm: {
                    expireTime: ''
                },
           }
       },
       mounted() {
           this.getList();
       },
       methods: {
           resetForm() {
               this.$refs['powerForm'].resetFields();
           },
           async powerSubmit() {
               const ids = this.$refs.tableRef.selection.map(item=>item.id).join(',')
               const result = await settingTenant(this.powerForm.accountNumber,format(this.powerForm.expireTime),ids);
               console.log(result);
               if(result.code === 200) {
                   this.$message.success('配置成功');
                   this.powerDialog = false;
                   this.getList();
               }
           },
           getList() {
               getTenantList(this.queryParams).then(res=>{
               if(res.code === 200) {
                   this.tableData = res.data.records;
                   this.total = res.data.total
               }
            })
           },
            // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
           handleAdd() {
               this.title = '新增';
               this.isView = false;
               this.tenantModal = true;
           },
           handleView(row) {
               this.title = '查看';
               this.isView = true;
               this.tenantForm = row;
               this.tenantModal = true;
           },
           handleEdit(row) {
               this.title = '编辑';
               this.isView = false;
               this.tenantForm = row;
               this.tenantModal = true;
           },
           async handleSetting() {
               if(this.$refs.tableRef.selection.length===0) {
                   this.$message.warning('请至少选择一条数据');
                   return;
               }
               const ids = this.$refs.tableRef.selection.map(item=>item.id).join(',');
               const result = await getTenantDetail(ids);
               if(result.code === 200) {
                   this.powerForm = result.data;
                   this.powerDialog = true;
               }
           },
             handleDel(ids) {
                let tenantIds;
                typeof ids === 'string'?tenantIds=ids:tenantIds=ids.map(item=>item.id).toString();
                if(tenantIds.length===0) {
                    this.$message({
                        type: 'error',
                        message: '请至少选择一条数据'
                    })
                    return;
                }
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        const result = await deleteTenant(tenantIds);
                        if(result.code === 200) {
                             this.$message({
                                type: 'success',
                                message: '删除成功!'
                           });
                          this.getClientData();
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
           beforeAvatarUpload() {},
           handleAvatarSuccess() {},
            handleSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                if (valid) {
                     saveTenantForm(this.tenantForm).then(res=>{
                        if(res.code === 200) {
                             this.$refs['tenantForm'].resetFields();
                                this.$message({
                                    message: '保存成功',
                                    type: 'success'
                                });
                                this.tenantModal = false;
                                this.getList();
                        }
                    })
                } else {
                    return false;
                }
              });
           },
       }
    }
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .pagination-container {
    padding: 10px;
    text-align: right;
}
</style>